package com.sky.task;

import com.github.pagehelper.Page;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;


/**
 * 用于处理订单超时，和订单自动设置完成
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单
     *
     * @return
     */
    @Scheduled(cron = "0 0/1 * * * ? ")//每隔一分钟进行检查
    public void OrderTimeoutTask() {
        //支付状态
        Integer status = Orders.PENDING_PAYMENT;
        //当前时间-15分钟，最晚下单时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> list = orderMapper.queryTimeout(status, time);
        log.info("检查超时订单");
        if (list != null && list.size() > 0) {
            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时");
                orders.setCancelTime(LocalDateTime.now());
                //log.info("订单【{}】超时", orders.getNumber());
                //修改
                orderMapper.updateData(orders);
            }
        }
    }

    /**
     * 处理管理员每天忘记点击已完成
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void AutoSetComplete() {
        //派送状态
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        //TODO 时间没看懂
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> list = orderMapper.queryForAutoSetComplete(status, time);
        if (list != null && list.size() > 0) {
            for (Orders orders : list) {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
                //修改
                orderMapper.updateData(orders);
            }
        }
    }
}
